//
//  UrlSchemeHandler.m
//  itboye2015002
//
//  Created by hebidu on 15/9/20.
//  Copyright © 2015年 Boye. All rights reserved.
//

#import "BoyeUrlSchemeHandler.h"

// 控制器
#import "ConfirmPayVC.h"
#import "PayOrderModel.h"
@implementation BoyeUrlSchemeHandler

+ (BOOL)handleOpenURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    
    // 判断是否是调用
    if ([[url scheme] isEqualToString:APP_SCHEME]) {

        /*
         字典中的键值对
         UIApplicationOpenURLOptionsOpenInPlaceKey = 0;
         UIApplicationOpenURLOptionsSourceApplicationKey = "com.itboye.sunsun-china"; // boundle id
         */
        
        [self handle:url options:options];
        
        return YES;
    }
    
    return NO;
}

+ (void)handle:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    
    // 获得 ? 后面的参数字符串
    NSString *query = [url query];
    
    // 获得了参数字典
    NSDictionary *params = [self parseURLParams:query];
    
    // url的类型
    NSString *key = params[@"type"];
    
    NSLog(@"url参数:%@", params);
    
    // 根据类型来跳转
    if ([key isEqualToString:@"SUNSUN_ALIPAY_FOR_SCOREGOODS"]) { // 积分商城
        
        [self _gotoPayVC:params];
    }
    else if ([key isEqualToString:@"SUNSUN_RED_ENVELOPE"]) { // 红包
        
    }
}

// 分解参数
+ (NSDictionary *)parseURLParams:(NSString *)query{
    
    NSArray *paramsAry = [query componentsSeparatedByString:@"&"];
    NSMutableDictionary *paramsDic = [[NSMutableDictionary alloc] init];
    for (NSString *params_keyValue in paramsAry) {
        NSArray *keyValue = [params_keyValue componentsSeparatedByString:@"="];
        if (keyValue.count == 2) {
            
            // %E8%AE%A2%E5%8D -> 订单     对这样的字符串进行解码
            NSString *value = [[keyValue lastObject] stringByRemovingPercentEncoding];

            [paramsDic setObject:value forKey:[keyValue firstObject]];
        }
    }
    return [paramsDic copy];
}




#pragma mark - 跳转
+ (void)_gotoPayVC:(NSDictionary *)params {
    
    PayOrderModel *model = [[PayOrderModel alloc] initContentWithDic:params];
    ConfirmPayVC *vc = [[ConfirmPayVC alloc] init];
    vc.payOrderModel = model;
    
    MainTabBarController *main = (MainTabBarController *)_APP_KEYWINDOW.rootViewController;
    if (main != nil){
        [main.selectedViewController pushViewController:vc animated:YES];
    }
}

@end
